package cn.itcast.bos.web.action.take_delivery;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.service.base.PromotionService;
import cn.itcast.bos.web.action.common.BaseAction;

@Controller
@Namespace("/")
@Scope("prototype")
@ParentPackage("json-default")
public class PromotionAction extends BaseAction<Promotion>{
	
	//接收文件上传项
	private File titleImgFile;
	private String titleImgFileFileName;
	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}
	
	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}

	//注入service层
	@Autowired
	private PromotionService promotionService;

	@Action(value="promotion_save",results={
			@Result(name="success",type="redirect",
					location="./pages/take_delivery/promotion.html")
	})
	public String save() throws IOException{
		System.err.println("图片名称:====="+titleImgFileFileName);
		System.err.println("图片文件=="+titleImgFile.getName());
		
		//宣传图上传,在数据表中保存 宣传图路径  savePath和saveUrl
		String savePath=ServletActionContext.getServletContext().getRealPath("/upload/");
		String saveUrl=ServletActionContext.getRequest().getContextPath()+"/upload/";
		
		//生成随机图片名称
		UUID uuid=UUID.randomUUID();
		//截取文件名称的后缀 
		String ext=titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
		String randomFileName=uuid+ext;
		//保存图片(绝对)
		FileUtils.copyFile(titleImgFile, new File(savePath+"/"+randomFileName));
		
		//将相对工程路径保存到model中
		model.setTitleImg(ServletActionContext.getRequest().getContextPath()+"/upload/"+randomFileName);
		//调用service层进行保存model对象`
		promotionService.save(model);
		return SUCCESS;
	}
	@Action(value="promotion_pageQuery",results={
			@Result(name="success",type="json")
	})
	public String pageQuery(){
		Pageable pageable=new PageRequest(page-1, rows);
		Page<Promotion> page=promotionService.findAll(pageable);
		//压入值栈
		pushToValueStack(page);
		
		return SUCCESS;
	}
	
	
}
